import React from 'react';
import { Editor, EditorState, RichUtils, convertToRaw, CompositeDecorator,Modifier } from 'draft-js';
import BlockStyleControls from './BlockStyleControls'
import InlineStyleControls from './InlineStyleControls'

import '../../node_modules/draft-js/dist/Draft.css'
import './RichEditor.css'

// Custom overrides for "code" style.
const styleMap = {
  CODE: {
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
    fontSize: 16,
    padding: 200,
  },
};

function findLinkEntities(contentBlock, callback, contentState) {

  contentBlock.findEntityRanges(
    (character) => {
      const entityKey = character.getEntity();
      return (
        entityKey !== null &&
        contentState.getEntity(entityKey).getType() === 'LINK'
      );
    },
    callback
  );
}

const Link = (props) => {
  const { url } = props.contentState.getEntity(props.entityKey).getData();
  return (
    <a href={url} style={{ color: 'red', cursor: "pointer" }} onClick={() => { window.open(url) }} >
      {props.children}
    </a>
  );
};

//for debug
window.convertToRaw = convertToRaw

class MyEditor extends React.Component {
  constructor(props) {
    const decorator = new CompositeDecorator([
      {
        strategy: findLinkEntities,
        component: Link,
      },
    ]);

    super(props);
    this.state = { editorState: EditorState.createEmpty(decorator) };
    this.focus = () => this.refs.editor.focus();
    this.onChange = (editorState) => {
      this.setState({ editorState })
      //for debug
      window.__editorState = editorState
    };

  }

  handleKeyCommand = (command) => {
    const { editorState } = this.state;
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      this.onChange(newState);
      return true;
    }
    return false;
  }
  onTab=(e)=> {
    const maxDepth = 4;
    this.onChange(RichUtils.onTab(e, this.state.editorState, maxDepth));
  }
  toggleBlockType=(blockType)=> {
    this.onChange(
      RichUtils.toggleBlockType(
        this.state.editorState,
        blockType
      )
    );
  }
  toggleInlineStyle=(inlineStyle) =>{
    this.onChange(
      RichUtils.toggleInlineStyle(
        this.state.editorState,
        inlineStyle
      )
    );
  }

  addLink = () => {
    let url = prompt('请输入链接')
    
    if(!url){
      return;
    }
    const {editorState} = this.state
    
    const contentState = editorState.getCurrentContent().createEntity('LINK', 'Immutable', { url: url })
    this.setState({
      editorState: RichUtils.toggleLink(
        editorState,
        editorState.getSelection(),
        contentState.getLastCreatedEntityKey()
      )
    }, () => {
      setTimeout(() => this.refs.editor.focus(), 0);
    });
  }

  test =()=>{
    const {editorState} = this.state
    const contentState = Modifier.insertText(editorState.getCurrentContent(),editorState.getSelection(),"test")

    // console.log(editorState.getCurrentContent().lastChangeType,"current")
    // console.log(contentState.lastChangeType,"new")    

    this.onChange(EditorState.push(editorState,contentState,undefined))
    
  }

  render() {

    const { editorState } = this.state;
    // If the user changes block type before entering any text, we can
    // either style the placeholder or hide it. Let's just hide it now.
    let className = 'RichEditor-editor';
    var contentState = editorState.getCurrentContent();
    if (!contentState.hasText()) {
      if (contentState.getBlockMap().first().getType() !== 'unstyled') {
        className += ' RichEditor-hidePlaceholder';
      }
    }

    return (
      <div className="RichEditor-root">
        <BlockStyleControls
          editorState={editorState}
          onToggle={this.toggleBlockType}
        />
        <InlineStyleControls
          editorState={editorState}
          onToggle={this.toggleInlineStyle}
        />
        <button onClick={this.addLink}>添加link</button>
        <button onClick={this.test}>测试</button>
        <div className={className} onClick={this.focus}>
          <Editor
            blockStyleFn={getBlockStyle}
            customStyleMap={styleMap}
            editorState={editorState}
            handleKeyCommand={this.handleKeyCommand}
            onChange={this.onChange}
            onTab={this.onTab}
            placeholder="Tell a story..."
            ref="editor"
            spellCheck={true}
          />
        </div>
      </div>
    );


  }

}


function getBlockStyle(block) {
  switch (block.getType()) {
    case 'blockquote': return 'RichEditor-blockquote';
    default: return null;
  }
}


export default MyEditor